<template>
  <el-dialog v-model="dialogFormVisible" :show-close="false" :close-on-click-modal="false" width="80%"  top="1vh">
    <template v-slot:header>
      <div class="flex justify-space-between align-center" style="background: #f5f7fa; padding: 10px">
        <div class="flex1" style="padding: 0 20px;">
          <el-steps
              :space="200"
              :active="active"
              align-center
              simple
          >
            <el-step title="基础信息" class="cursor" :icon="Edit" @click="active=1"/>
            <el-step title="价格控制" class="cursor" :icon="UploadFilled" @click="active=2"/>
            <el-step title="附属信息" class="cursor" :icon="Picture" @click="active=3"/>
            <el-step title="发布控制" class="cursor" :icon="UploadFilled" @click="active=4"/>
            <el-step title="客服群信息" class="cursor" :icon="Picture" @click="active=5"/>
          </el-steps>
        </div>
        <div>
          <el-button @click="handleCloseDialog" icon="remove">取消</el-button>
          <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">{{form.id?'修改':'保存'}}</el-button>
        </div>
      </div>
      <div style="padding:20px;background:#f5f7fa;margin-top: 10px;">
        <el-form v-loading="editLoading" ref="formRef" label-width="160px" :model="form" :rules="rules">
          <div v-show="active==1">
            <el-row>
              <el-col :span="8">
                <el-form-item label="分类：" required prop="categoryPid">
                  <el-cascader
                      style="width: 100%"
                      v-model="categoryIds"
                      ref="cascaderCatergoryRef"
                      @change="handleCatergoryChange"
                      :props="{ checkStrictly: true, emitPath: true, multiple: false, value: 'id', label: 'title' }"
                      :options="categoryList"
                  />
                </el-form-item>
                <el-form-item label="类型：" required prop="downloadstype">
                  <el-select
                      v-model="form.downloadstype"
                      style="width: 100%"
                      placeholder="请选择类型"
                  >
                    <el-option v-for="item in downloadsTypes" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="标题：" required prop="title">
                  <el-input v-model="form.title" maxlength="200" placeholder="帖文标题"/>
                </el-form-item>
                <el-form-item label="描述：" prop="description">
                  <el-input v-model="form.description" maxlength="200" type="textarea" placeholder="描述少于200字"/>
                </el-form-item>
                <el-form-item label="封面：" prop="img">
                  <div style="display: flex; flex-direction: column">
                    <div>
                      <kva-upload
                          v-model="form.img"
                          @success="handleUploadSuccess"
                          isvalid
                          path="downloads"
                          ref="imgUploadRef"
                      ></kva-upload>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="选择作者：" required prop="nickname" @click.stop="handleOpenAuthorDialog">
                  <el-input v-model="form.nickname" readonly maxlength="60" placeholder="作者昵称">
                    <template #append>
                      <el-button type="primary" icon="plus" @click.stop="handleOpenAuthorDialog">选择作者</el-button>
                    </template>
                  </el-input>
                  <el-input v-model="form.username" readonly maxlength="60" class="mt5" placeholder="作者用户名"></el-input>
                  <el-input v-model="form.uuid" readonly maxlength="60"  class="mt5" placeholder="作者唯一标识"></el-input>
                  <el-input v-model="form.userid" readonly maxlength="60"  class="mt5" placeholder="作者ID"></el-input>
                  <el-input v-model="form.avatar" readonly maxlength="60"  class="mt5" placeholder="作者头像"></el-input>
                </el-form-item>
                <el-form-item label="标签：" prop="tags">
                  <el-input v-model="form.tags" maxlength="100" placeholder="标签"/>
                </el-form-item>
                <el-form-item label="收藏数：" prop="favNum">
                  <el-input-number
                      class="w100"
                      v-model="form.favNum"
                      maxlength="10"
                      controls-position="right"
                      placeholder="收藏数"
                  />
                </el-form-item>
                <el-form-item label="喜欢数：" prop="likeNum">
                  <el-input-number
                      class="w100"
                      v-model="form.likeNum"
                      maxlength="10"
                      controls-position="right"
                      placeholder="喜欢数"
                  />
                </el-form-item>
                <el-form-item label="评论数：" prop="commentNum">
                  <el-input-number
                      class="w100"
                      v-model="form.commentNum"
                      maxlength="10"
                      controls-position="right"
                      placeholder="评论数"
                  />
                </el-form-item>
                <el-form-item label="预览数：" prop="viewcount">
                  <el-input-number
                      class="w100"
                      v-model="form.viewcount"
                      maxlength="10"
                      controls-position="right"
                      placeholder="预览数"
                  />
                </el-form-item>
                <el-form-item label="购买人数：" prop="buyNum">
                  <el-input-number
                      class="w100"
                      v-model="form.buyNum"
                      maxlength="10"
                      controls-position="right"
                      placeholder="购买人数"
                  />
                </el-form-item>
                <el-form-item label="下载数量：" prop="downloadNums">
                  <el-input-number
                      class="w100"
                      v-model="form.downloadNums"
                      maxlength="10"
                      controls-position="right"
                      placeholder="评论数"
                  />
                </el-form-item>
                <el-form-item label="关联视频ID：" prop="videoid">
                  <el-input v-model="form.videoid" maxlength="100" placeholder="关联视频ID"/>
                </el-form-item>
              </el-col>
              <el-col :span="1"></el-col>
              <el-col :span="15">
                <tinymce
                    :articleId="form.id"
                    :id="editorId"
                    :key="datetime"
                    :showmedia="false"
                    v-model:content="form.content"
                    @success="handleEditorContent"
                    height="calc(100vh - 300px)"
                ></tinymce>
              </el-col>
            </el-row>
          </div>
          <div v-show="active==2">
            <el-col span="24">
              <el-form-item label="可见性：" prop="vipFlag">
                <el-radio-group v-model="form.vipFlag">
                  <el-radio :label="1">所有人可见</el-radio>
                  <el-radio :label="2">VIP可见</el-radio>
                  <el-radio :label="3">SVIP可见</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="支付类型：" prop="payFlag">
                <el-radio-group v-model="form.payFlag">
                  <el-radio :label="1">免费</el-radio>
                  <el-radio :label="2">收费</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="购买价格：" prop="price">
                <el-input v-model="form.price" maxlength="40" placeholder="购买价格"/>
              </el-form-item>

              <el-form-item label="真实价格：" prop="realprice">
                <el-input v-model="form.realprice" maxlength="40" placeholder="真实价格"/>
              </el-form-item>

              <el-form-item label="学习金币：" prop="coin">
                <el-input v-model="form.coin" maxlength="40" placeholder="学习金币"/>
              </el-form-item>

              <el-col span="24">
                <el-form-item label="网盘地址：" prop="panLink">
                  <el-input v-model="form.panLink" maxlength="400" placeholder="网盘地址"/>
                </el-form-item>

                <el-form-item label="网盘密码：" prop="panPwd">
                  <el-input v-model="form.panPwd" maxlength="20" placeholder="网盘密码"/>
                </el-form-item>
              </el-col>
            </el-col>
          </div>
          <div v-show="active==3">
            <el-col span="24">
              <el-form-item label="打开方式：" prop="mode">
                <el-radio-group v-model="form.mode">
                  <el-radio :label="1">内站打开</el-radio>
                  <el-radio :label="2">站外打开</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="站外访问地址：" prop="url">
                <el-input v-model="form.url" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>

              <el-form-item label="官网地址：" prop="netLink">
                <el-input v-model="form.netLink" maxlength="400" placeholder="官网地址"/>
              </el-form-item>

              <el-form-item label="体验地址：" prop="tryLink">
                <el-input v-model="form.tryLink" maxlength="400" placeholder="体验地址"/>
              </el-form-item>

              <el-form-item label="其他信息：" prop="otherinfo">
                <el-input v-model="form.otherinfo" placeholder="其他信息" type="textarea" rows="20"/>
              </el-form-item>
            </el-col>
          </div>
          <div v-show="active==4">
            <el-col span="24">
              <el-form-item label="是否最新：" prop="newFlag">
                <el-radio-group v-model="form.newFlag">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="是否热门：" prop="hotFlag">
                <el-radio-group v-model="form.hotFlag">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>


              <el-form-item label="是否允许评论：" prop="commentFlag">
                <el-radio-group v-model="form.commentFlag">
                  <el-radio :label="1">允许</el-radio>
                  <el-radio :label="0">禁止</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="是否推荐：" prop="pushFlag">
                <el-radio-group v-model="form.pushFlag">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>


              <el-form-item label="发布状态：" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="1">上架中</el-radio>
                  <el-radio :label="0">下架中</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="是否显示专栏：" prop="specialFlag">
                <el-radio-group v-model="form.specialFlag">
                  <el-radio :label="1">显示</el-radio>
                  <el-radio :label="0">不显示</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="隐藏显示课程：" prop="showFlag">
                <el-radio-group v-model="form.showFlag">
                  <el-radio :label="1">显示</el-radio>
                  <el-radio :label="0">隐藏</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </div>
          <div v-show="active==5">
            <el-col span="24">
              <el-form-item label="微信和QQ群是否打开：" prop="clientFlag">
                <el-radio-group v-model="form.clientFlag">
                  <el-radio :label="1">开启</el-radio>
                  <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="微信/qq群号：" prop="clientLinkName">
                <el-input v-model="form.clientLinkName" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq群连接：" prop="clientLink">
                <el-input v-model="form.clientLink" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq群二维码：" prop="clientLinkImg">
                <kva-upload path="clients" @success="handleUploadSuccessW1" ref="uploadRef11" :oldname="form.clientLinkImg"></kva-upload>
              </el-form-item>
              <el-form-item label="微信/qq2群号：" prop="qqLinkName">
                <el-input v-model="form.qqLinkName" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq2群连接：" prop="qqLinkCode">
                <el-input v-model="form.qqLinkCode" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq2群二维码：" prop="qqLinkImg">
                <kva-upload path="clients" @success="handleUploadSuccessW2" ref="uploadRef22" :oldname="form.qqLinkImg"></kva-upload>
              </el-form-item>
              <el-form-item label="微信/qq3群号：" prop="weixinLinkName">
                <el-input v-model="form.weixinLinkName" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq3群连接：" prop="weixinLink">
                <el-input v-model="form.weixinLink" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="微信/qq3群二维码：" prop="weixinLinkImg">
                <kva-upload path="clients" @success="handleUploadSuccessW3" ref="uploadRef33" :oldname="form.weixinLinkImg"></kva-upload>
              </el-form-item>
              <el-form-item label="公众号是否打开：" prop="opengz">
                <el-radio-group v-model="form.opengz">
                  <el-radio :label="1">开启</el-radio>
                  <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="公众号名称：" prop="weixingzcode">
                <el-input v-model="form.weixingzcode" maxlength="400" placeholder="站外访问地址"/>
              </el-form-item>
              <el-form-item label="公众号二维码：" prop="weixingzimg">
                <kva-upload path="clients" @success="handleUploadSuccessW4" ref="uploadRef44" :oldname="form.weixingzimg"></kva-upload>
              </el-form-item>
            </el-col>
          </div>
        </el-form>
      </div>
      <teleport to="body"><kva-select-authors ref="authorRef" @select="handleSelectAuthor"></kva-select-authors></teleport>
    </template>
  </el-dialog>
</template>
<script setup>
import {getById, saveUpdate} from '@/api/download/index.js'
import KVA from '@/utils/kva.js'
import debounce from '@/utils/debounce'
const authorRef = ref({})
const emits = defineEmits(['load'])
const downloadsTypes = ref([{label:"基础课",value:1},{label:"进阶课",value:2},{label:"实战课",value:3},{label:"面试课",value:4}])
// 控制弹窗得显示
const dialogFormVisible = ref(false)
const tinymceRef = ref({})
const uploadRef11 = ref({})
const uploadRef22 = ref({})
const uploadRef33 = ref({})
const uploadRef44 = ref({})
const active = ref(1)
const datetime = ref(new Date().getTime())
const editorId = ref('acontenteditor' + new Date().getTime())
// 这个数据模型
let form = ref({
  title:'',
  url:'',
  content:'',
  tags:'',
  img:'',
  description:'',
  viewcount:0,
  downloadNums:0,
  commentFlag:0,
  uuid:'',
  avatar:'',
  nickname:'',
  username:'',
  userid:0,
  status:1,
  favNum:0,
  likeNum:0,
  commentNum:0,
  buyNum:0,
  price:0,
  coin:0,
  realprice:0,
  newFlag:0,
  hotFlag:0,
  pushFlag:0,
  vipFlag:1,
  mode:1,
  netLink:'',
  panLink:'',
  panPwd:'',
  tryLink:'',
  payFlag:1,
  downloadstype:'',
  otherinfo:'{\n' +
      '  "source":"xxx",\n' +
      '  "teacher":"xxx",\n' +
      '  "timer":"xxx小时",\n' +
      '  "price":"￥1000",\n' +
      '  "link":"https://www.xxxx.com/xxx.html",\n' +
      '  "period":" 永久有效",\n' +
      '  "buynum":"100",\n' +
      '  "downnum":"100",\n' +
      '  "uptime":"2024年03月08日"\n' +
      '} ',
  categoryId:0,
  categoryName:'',
  categoryPid:0,
  categoryPname:'',
  clientLink:'',
  clientLinkName:'',
  clientLinkImg:'',
  qqLinkCode:'',
  qqLinkName:'',
  qqLinkImg:'',
  weixinLink:'',
  weixinLinkName:'',
  weixinLinkImg:'',
  clientFlag:1,
  opengz:1,
  weixingzcode:"",
  weixingzimg:"",
  videoid:"",
  specialFlag:1,
  showFlag:1
})
const imgUploadRef = ref({})
// 弹出标题
const title = ref('添加')
const editLoading = ref(false)
const editFlag = ref(false)
const suLoading = ref(false)
// 表单ref, 用于提交最终得验证处理
const formRef = ref({})
const imgArr = ref([])
// 分类信息
const categoryList = ref([])
const categoryIds = ref([])
const cascaderCatergoryRef = ref({})
// 表单验证
const rules = reactive({
  categoryPid: [{required: true, message: '请选择分类', trigger: 'blur'}],
  username: [{required: true, message: '请选择作者', trigger: 'blur'}],
  title: [{required: true, message: '请输入标题', trigger: 'blur'}]
})

// 打开修改密码的弹窗
const handleOpen = async (opid, cList) => {
  dialogFormVisible.value = true
  editLoading.value = true
  title.value = '添加'
  categoryList.value = cList
  if (opid) {
    title.value = '编辑'
    editFlag.value = true
    const resp = await getById(opid)
    editLoading.value = false
    form.value = resp.data
    imgUploadRef.value.toggleImgcover(resp.data.img)
    uploadRef11.value.toggleImgcover(resp.data.clientLinkImg)
    uploadRef22.value.toggleImgcover(resp.data.qqLinkImg)
    uploadRef33.value.toggleImgcover(resp.data.weixinLinkImg)
    uploadRef44.value.toggleImgcover(resp.data.weixingzimg)
    if (tinymceRef.value) {
      tinymceRef.value.setContent(resp.data.content)
    }
    if (resp.data.categoryId > 0) {
      categoryIds.value = [resp.data.categoryPid, resp.data.categoryId]
    } else {
      categoryIds.value = [resp.data.categoryPid]
    }
    title.value = '编辑【' + form.value.title + '】'
  } else {
    editLoading.value = false
  }
}

const handleEditorContent = (editor) => {
  tinymceRef.value = editor
  var content = localStorage.getItem("kva-download-add-content")
  if(editor)editor.setContent(content)
}

// 选择用户
const handleSelectAuthor = (user) => {
  form.value.userid = user.id
  form.value.uuid = user.uuid
  form.value.avatar = user.avatar
  form.value.nickname = user.nickName
  form.value.username = user.userName
}

// 保存和修改
const handleSubmit = () => {
  suLoading.value = true
  debounce(() => {
    formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          if (imgArr.value && imgArr.value.length > 0) {
            form.value.imgList = imgArr.value.join(',')
          }
          await saveUpdate(form.value)
          suLoading.value = false
          // 提示保存成功
          KVA.notifySuccess(form.value.id ? '更新成功' : '保存成功')
          if(tinymceRef)tinymceRef.value.setContent("")
          localStorage.removeItem("kva-download-add-content")
          // 刷新方法
          emits('load')
          // 关闭弹窗
          handleClose()
          // 请空编辑器
        } catch (ex) {
          suLoading.value = false
        }
      } else {
        suLoading.value = false
      }
    })
  }, 600)
}


// 上传封面回调
const handleUploadSuccess = (data1, data2) => {
  form.value.img = data1
}

const handleClose = () => {
    form.value = {
      title: '',
      url: '',
      content: '',
      tags: '',
      img: '',
      description: '',
      viewcount: 0,
      downloadNums: 0,
      commentFlag: 0,
      downloadstype:'',
      uuid: '',
      avatar: '',
      nickname: '',
      username: '',
      userid: 0,
      status: 1,
      favNum: 0,
      likeNum: 0,
      commentNum: 0,
      buyNum: 0,
      price: 0,
      coin: 0,
      realprice: 0,
      newFlag: 0,
      hotFlag: 0,
      pushFlag: 0,
      vipFlag: 1,
      mode: 1,
      netLink: '',
      panLink: '',
      panPwd: '',
      tryLink: '',
      payFlag: 1,
      clientLink:'',
      clientLinkName:'',
      clientLinkImg:'',
      qqLinkCode:'',
      qqLinkName:'',
      qqLinkImg:'',
      weixinLink:'',
      weixinLinkName:'',
      weixinLinkImg:'',
      clientFlag:1,
      opengz:1,
      weixingzcode:"",
      weixingzimg:"",
      otherinfo:'{\n' +
      '  "source":"xxx",\n' +
      '  "teacher":"xxx",\n' +
      '  "timer":"xxx小时",\n' +
      '  "price":"￥1000",\n' +
      '  "link":"https://www.xxxx.com/xxx.html",\n' +
      '  "period":" 永久有效",\n' +
      '  "buynum":"100",\n' +
      '  "downnum":"100",\n' +
      '  "uptime":"2024年03月08日"\n' +
      '} ',
      categoryId: 0,
      categoryName: '',
      categoryPid: 0,
      categoryPname: '',
      videoid:"",
      specialFlag:1,
      showFlag:1
    }
  imgUploadRef.value.toggleImgcover("")
  editFlag.value = false
  title.value = ''
  imgArr.value = []
  active.value = 1
  categoryIds.value = []
  uploadRef11.value.toggleImgcover("")
  uploadRef22.value.toggleImgcover("")
  uploadRef33.value.toggleImgcover("")
  uploadRef44.value.toggleImgcover("")
  suLoading.value = false
  editLoading.value = false
  dialogFormVisible.value = false
  // 请空编辑器
  if(tinymceRef)tinymceRef.value.setContent("")
  formRef.value.resetFields()
}

const handleCloseDialog = () => {
  KVA.confirm('提示', '更改后的内容尚未保存，确定要退出吗？', {
    confirmButtonText: '退出',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleClose()
  })
}

// 打开作者框
const handleOpenAuthorDialog = () => {
  authorRef.value.handleOpen(form.value?.authorId)
}

watch(categoryIds, (newval) => {
  var cids = newval
  form.value.categoryPid = cids[0]
  form.value.categoryId = cids[1]
})

watch(form,()=>{
  if(form.value.content) {
    localStorage.setItem("kva-download-add-content", form.value.content)
  }
},{deep:true,immediate:true})

const handleCatergoryChange = async (data) => {
  var texts = cascaderCatergoryRef._rawValue.getCheckedNodes()[0].text.split('/')
  form.value.categoryPname = texts[0]
  form.value.categoryName = texts[1]
}

const handleUploadSuccessW1 = (path, data) => {
  form.value.clientLinkImg = path
}

const handleUploadSuccessW2 = (path, data) => {
  form.value.qqLinkImg = path
}

const handleUploadSuccessW3 = (path, data) => {
  form.value.weixinLinkImg = path
}

const handleUploadSuccessW4 = (path, data) => {
  form.value.weixingzimg = path
}

// 把弹出打开得方法暴露给父组件进行调用
defineExpose({
  handleOpen
})
</script>
<style>
.el-dialog__body {
  padding-bottom: 10px !important;
}

.showullist {
  list-style: none;
  display: grid;
  grid-gap: 10px;
  /*设置三行宽度都为100px；*/
  grid-template-columns: 100px 100px 100px;
  margin-top: 20px;
}

.showullist li {
  position: relative;
  border: 4px solid #eee;
  display: flex;
  align-items: center;
}

.showullist li .img-link {
  width: 100%;
  object-fit: cover;
}

.showullist li .close {
  position: absolute;
  top: -18px;
  right: -10px;
}
</style>
